﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Threading;

namespace TestMySqlConnetPoll
{
    public class ObjValue
    {
        public int DecimalNum = 0;
        public float Value = -1;     //直接返回浮点数
        public string ValueType = "";   //返回值的类型
    }
    public class ObjRealTimeValue
    {
        public string DevName = "";  //设备名称
        public List<ObjValue> DevValue = new List<ObjValue>();
    }

    public class objRealCurveGybdcqx
    {
        public string DevName = "";
        public DateTime time = new DateTime();
        public int DotNum = 0;
        public List<float> dValue = new List<float>();
    }

    public class MessageInfoEventArgs : EventArgs
    {
        public MessageInfoEventArgs(string ErrorString)
        {
            this.ErrorString = ErrorString;
        }
        public string ErrorString { get; private set; }
    }

    static public class c_RealTimeValue     //实时值类
    {
        static public event EventHandler<MessageInfoEventArgs> MessageInfo;
        /// <summary>
        /// 定义实时值变量，以设备类型做为键值，所有的实时值都放在该变量中。
        /// </summary>
        static public Dictionary<string, List<ObjRealTimeValue>> RealTimeValue_Analog = new Dictionary<string, List<ObjRealTimeValue>>();  //显示层实际用的值

        static public DataTable KglRealTimeTable = new DataTable("开关量实时值");         //显示层实际用的开关量实时值表格
        static public byte[] ReceiveKGLData = new byte[2000];    //从外部接口获得的开关量原始值，站场图，状态图用的数据

        static public DataTable JyRealTimeTable = new DataTable("电缆绝缘测试值");        //显示层用的绝缘实时值表格

        static public DataTable LlRealTimeTable = new DataTable("电源漏流测试值");         //显示层用的漏流实时值表格

        static public List<ObjAlaram> ReceiveAlarmData = new List<ObjAlaram>();         //获得的报警数据，显示层用的数据

        static public objRealCurveGybdcqx GybdcqxRealValue = new objRealCurveGybdcqx();

        //列控实时表格数据
        //public Dictionary<objLkKey, objLKHostHardTable> HostHardwarePlatform = new Dictionary<objLkKey, objLKHostHardTable>();

        static public DataTable HostHardwarePlatform = new DataTable("列控中心主机硬件平台");
        static public DataTable LianSuoJieKouRouteInfo = new DataTable("列控中心与联锁接口进路信息");
        static public DataTable LianSuoGaiFangCommandInfo = new DataTable("列控中心与联锁改方命令信息");
        static public DataTable LianSuoGaiFangCommandRet = new DataTable("列控中心与联锁改方回执信息");
        static public DataTable ZhanJianGaiFangCommandInfo = new DataTable("列控中心站间改方命令信息");
        static public DataTable ZhanJianGaiFangCommandRet = new DataTable("列控中心站间改方回执信息");
        static public DataTable ZhanJianBoundaryInfo = new DataTable("列控中心站间边界信息");
        static public DataTable SendToLianSuoInfo = new DataTable("发送给联锁的无配线站区间方向口信息");
        static public DataTable TemporaryLimitSpeedState = new DataTable("列控中心临时限速状态");
        static public DataTable SectionEncodeInfo = new DataTable("轨道区段编码信息");
        static public DataTable TransponderEncodeInfo = new DataTable("应答器报文编码信息");
        static public DataSet Statue_Info = new DataSet("全体状态信息");

        //以下为本类用的存储数据用的变量
        static private Dictionary<string, List<Int16>> ReceiveAnalogData = new Dictionary<string, List<short>>();        //从外部接口得到的原始数据        

        static private List<objRevCommandType> ReceiveCommandData = new List<objRevCommandType>();

        static private JyLlCyTable JyLlobject = new JyLlCyTable();

        static private List<objRevLkType> ReceiveLkData = new List<objRevLkType>(); 

        /// <summary>
        /// 外部函数，初始化实时值表
        /// </summary>
        static public void InitRealTimeData()
        {
            InitKglRealTimeTable();             //初始化开关量实时值表
            InitMsgGatherRealTimeValue();       //初始化模拟量实时值表
            InitJyRealTimeTable();              //绝缘
            InitLlRealTimeTable();              //漏流
            c_LK.InitHostHardwarePlatform(ref HostHardwarePlatform);
            c_LK.InitLianSuoGaiFangCommandInfo(ref LianSuoGaiFangCommandInfo);
            c_LK.InitLianSuoGaiFangCommandRet(ref LianSuoGaiFangCommandRet);
            c_LK.InitLianSuoJieKouRouteInfo(ref LianSuoJieKouRouteInfo);
            c_LK.InitSectionEncodeInfo(ref SectionEncodeInfo);
            c_LK.InitSendToLianSuoInfo(ref SendToLianSuoInfo);
            c_LK.InitTemporaryLimitSpeedState(ref TemporaryLimitSpeedState);
            c_LK.InitTransponderEncodeInfo(ref TransponderEncodeInfo);
            c_LK.InitZhanJianBoundaryInfo(ref ZhanJianBoundaryInfo);
            c_LK.InitZhanJianGaiFangCommandInfo(ref ZhanJianGaiFangCommandInfo);
            c_LK.InitZhanJianGaiFangCommandRet(ref ZhanJianGaiFangCommandRet);
            c_LK.InitStatueInfo(ref Statue_Info);
        }

        /// <summary>
        /// 外部函数，刷新实时值
        /// </summary>
        static public void RefreshRealTimeData()
        {
            RefreshAnalogDataFormQueue();
            RefreshAlarmDataFromQueue();
            RefreshKglDataFromQueue();
            RefreshCommandRetFromQueue();
            RefreshLkFromQueue();
            RefreshGybdcqxQueue();
        }

        static private void RefreshGybdcqxQueue()
        {
            bool flag = false;
            objRevGybdcQxType t = new objRevGybdcQxType();
            lock (c_ReceiveData.RevGybdcQxQueue)
            {
                int len = c_ReceiveData.RevGybdcQxQueue.Count;
                while (len > 0)
                {
                    len--;
                    t = c_ReceiveData.RevGybdcQxQueue.Dequeue();        //一般只有一条曲线
                    flag = true;
                }
                c_ReceiveData.RevGybdcQxQueue.TrimExcess();
            }
            if (flag == true)
            {
                int devNo = t.devNo;
                GybdcqxRealValue.DevName = c_Device.GetGybdcDyDevName(devNo);
                GybdcqxRealValue.DotNum = t.dotNum;
                GybdcqxRealValue.time = MySql.Time_tToDateTime(t.time);
                for (int i = 0; i < t.v.Count; i++)
                {
                    int v = t.v[i] + t.v[i + 1] << 8;
                    i++;
                    ObjValue o = ConvertAnalogValue("高压不对称",(Int16)v);
                    float f = o.Value;
                    GybdcqxRealValue.dValue.Add(f);
                }
            }
        }

        static private void RefreshAnalogDataFormQueue()  //从队列中把模拟量数据加入到接收缓冲区中.
        {
            int len = c_ReceiveData.RevAnalogQueue.Count;
            while (len > 0)
            {
                len--;
                objRevAnalogType TmpRevData  = new objRevAnalogType();
                lock (c_ReceiveData.RevAnalogQueue)
                {
                    TmpRevData = c_ReceiveData.RevAnalogQueue.Dequeue();
                }
                string KeyString = TmpRevData.AnalogTypeName;
                if (ReceiveAnalogData.ContainsKey(KeyString)) ReceiveAnalogData[KeyString].Clear();
                ReceiveAnalogData.Add(KeyString, TmpRevData.ValueList);
            }
            c_ReceiveData.RevAnalogQueue.TrimExcess();  //重新设置队列的容量.
            DisposeAnalogRealTimeValue();     //把收到的实时值转换成显示用数据.
        }

        static public void RefreshKglDataFromQueue()
        {
            lock (c_ReceiveData.RevKGLQueue)
            {
                int len = c_ReceiveData.RevKGLQueue.Count;
                while (len > 0)
                {
                    len--;
                    List<byte> t = new List<byte>();

                    t = c_ReceiveData.RevKGLQueue.Dequeue();

                    ReceiveKGLData.Initialize();
                    t.CopyTo(ReceiveKGLData);
                }
                c_ReceiveData.RevKGLQueue.TrimExcess();
            }
            DisposeKglRealTimeValue();
        }

        static private void RefreshAlarmDataFromQueue()
        {
            lock (c_ReceiveData.RevAlarmQueue)
            {
                int len = c_ReceiveData.RevAlarmQueue.Count;
                if (len > 0) ReceiveAlarmData.Clear();
                while (len > 0)
                {
                    len--;
                    ObjAlaram obj = new  ObjAlaram();
                    obj = c_ReceiveData.RevAlarmQueue.Dequeue();
                    ReceiveAlarmData.Add(obj);
                }
                c_ReceiveData.RevAlarmQueue.TrimExcess();
            }
            //该处不再做进一步处理，显示层自己去形成表格
        }

        static private void RefreshCommandRetFromQueue()
        {
            lock (c_ReceiveData.RevCommandRet)
            {
                int len = c_ReceiveData.RevCommandRet.Count;
                if (len > 0) ReceiveCommandData.Clear();
                while (len > 0)
                {
                    len--;
                    objRevCommandType obj = c_ReceiveData.RevCommandRet.Dequeue();
                    ReceiveCommandData.Add(obj);
                }
                c_ReceiveData.RevCommandRet.TrimExcess();
            }
            DisposeCommandRetValue();
        }

        static private void RefreshLkFromQueue()
        {
            lock (c_ReceiveData.RevLkQueue)
            {
                int len = c_ReceiveData.RevLkQueue.Count;
                if(len>0) ReceiveLkData.Clear();
                while(len>0)
                {
                    len--;
                    objRevLkType obj = new objRevLkType();
                    obj = c_ReceiveData.RevLkQueue.Dequeue();
                    ReceiveLkData.Add(obj);
                }
                c_ReceiveData.RevLkQueue.TrimExcess();
            }
            DisposeLkRealTimeValue();
        }
        /// <summary>
        /// 初始化实时值列表，以设备表的结构初始化
        /// </summary>
        static private void InitMsgGatherRealTimeValue()
        {
            foreach(KeyValuePair<string,objMsgGatherStruct> li in c_Device.DeviceMsgGather)
            {
                string DevTypeName = li.Key;
                List<ObjRealTimeValue> tmpRealTimeValueList = new List<ObjRealTimeValue>();
                for (int i = 0; i < li.Value.DevList.Count; i++)
                {
                    ObjRealTimeValue tmpRealTimeValue = new ObjRealTimeValue();
                    tmpRealTimeValue.DevName = li.Value.DevList[i].DevName;
                    tmpRealTimeValueList.Add(tmpRealTimeValue);
                }
                RealTimeValue_Analog.Add(DevTypeName, tmpRealTimeValueList);
            }            
        }

        /// <summary>
        /// 初始化实时开关量表
        /// </summary>
        static private void InitKglRealTimeTable()
        {
            KglRealTimeTable.Columns.Add("序号", typeof(string));
            KglRealTimeTable.Columns.Add("名称", typeof(string));
            KglRealTimeTable.Columns.Add("类型", typeof(string));
            KglRealTimeTable.Columns.Add("状态", typeof(string));
            KglRealTimeTable.Columns.Add("分机号", typeof(int));
            //KglRealTimeTable.Columns.Add("分机内序号", typeof(int));
            for (int i = 0; i < c_Device.KGL_Config.Count; i++)
            {
                DataRow dr = KglRealTimeTable.NewRow();
                dr["序号"] = i + 1;
                dr["名称"] = c_Device.KGL_Config[i].Name;
                int type = c_Device.KGL_Config[i].Type;
                if (type == 0) dr["类型"] = "";
                else if (type == 1) dr["类型"] = "";
                else dr["类型"] = "";
                dr["状态"] = "";
                dr["分机号"] = c_Device.KGL_Config[i].FeiJiNo;
                //dr["分机内序号"] = c_Device.KGL_Config[i].
                KglRealTimeTable.Rows.Add(dr);
            }
        }

        static private void ThreadWaitJyRealTimeValue(object o)
        {
            int SleepCount = 10;
            while (true)
            {
                if (JyLlobject.Ready_JyNewstValue)
                {
                    foreach(string key in JyLlobject.Jy_NewstValueList.Keys)
                    {
                        DataRow dr = JyRealTimeTable.Rows.Find(key);
                        if (dr != null)
                        {
                            dr.BeginEdit();
                            dr["测试值(MΩ)"] = JyLlobject.Jy_NewstValueList[key].dValue.Value.ToString();
                            dr["测试时间"] = JyLlobject.Jy_NewstValueList[key].time;
                            dr.EndEdit();                            
                        }
                        else
                        {
                            MessageInfo(null, new MessageInfoEventArgs("绝缘设备名称不匹配"));
                        }
                    }
                    JyRealTimeTable.AcceptChanges();
                    break;
                }
                else if (JyLlobject.ErrorFlag != 0)
                {
                    //MessageBox.Show("绝缘最新值获取错误");
                    MessageInfo(null, new MessageInfoEventArgs("绝缘最新值获取错误"));
                    break;
                }
                else
                {                    
                    Thread.Sleep(500);
                    SleepCount--;
                    if (SleepCount == 0)
                    {
                        MessageInfo(null, new MessageInfoEventArgs("绝缘最新值超时错误"));
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 初始化绝缘实时值表格，初始填充表格，并查询数据库
        /// </summary>
        static private void InitJyRealTimeTable()
        {
            string s = "绝缘";
            JyRealTimeTable.Columns.Add("设备名称", typeof(string));
            JyRealTimeTable.Columns.Add("测试值(MΩ)", typeof(string));
            JyRealTimeTable.Columns.Add("测试时间", typeof(DateTime));
            foreach (string key in c_Device.DeviceMsgGather.Keys)
            {
                if (key.Contains(s))
                {
                    for (int i = 0; i < c_Device.DeviceMsgGather[key].DevList.Count; i++)
                    {
                        DataRow dr = JyRealTimeTable.NewRow();
                        dr["设备名称"] = c_Device.DeviceMsgGather[key].DevList[i].DevName;
                        dr["测试值(MΩ)"] = "未测试";
                        JyRealTimeTable.Rows.Add(dr);
                    }
                }
            }
            JyRealTimeTable.PrimaryKey = new DataColumn[] { JyRealTimeTable.Columns["设备名称"] };      //设置键值
            JyLlobject.ReadJyLlCyNewstValue(s);
//            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadWaitJyRealTimeValue), null);
        }
        /// <summary>
        /// 线程函数，等待查询数据库结束后，填充漏流的最新值表
        /// </summary>
        /// <param name="o"></param>
        static private void ThreadWaitLlRealTimeValue(object o)
        {
            int SleepCount = 10;
            while (true)
            {
                if (JyLlobject.Ready_LlNewstValue)
                {
                    foreach (string key in JyLlobject.Ll_NewstValueList.Keys)
                    {
                        DataRow dr = LlRealTimeTable.Rows.Find(key);
                        if (dr != null)
                        {
                            dr.BeginEdit();
                            dr["测试值(mA)"] = JyLlobject.Ll_NewstValueList[key].dValue.Value.ToString();
                            dr["测试时间"] = JyLlobject.Ll_NewstValueList[key].time;
                            dr.EndEdit();
                        }
                        else
                        {
                            MessageInfo(null, new MessageInfoEventArgs("漏流设备名称不匹配"));
                        }
                    }
                    JyRealTimeTable.AcceptChanges();
                    break;
                }
                else if (JyLlobject.ErrorFlag != 0)
                {
                    //MessageBox.Show("绝缘最新值获取错误");
                    MessageInfo(null, new MessageInfoEventArgs("漏流最新值获取错误"));
                    break;
                }
                else
                {
                    Thread.Sleep(500);
                    SleepCount--;
                    if (SleepCount == 0)
                    {
                        MessageInfo(null, new MessageInfoEventArgs("漏流最新值超时错误"));
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 初始化漏流的最新值，构建表格，并查询数据库，填充表格
        /// </summary>
        static private void InitLlRealTimeTable()
        {
            string s = "漏流";
            LlRealTimeTable.Columns.Add("设备名称", typeof(string));
            LlRealTimeTable.Columns.Add("测试值(mA)", typeof(string));
            LlRealTimeTable.Columns.Add("测试时间", typeof(DateTime));
            LlRealTimeTable.PrimaryKey = new DataColumn[] { LlRealTimeTable.Columns["设备名称"] };
            foreach (string key in c_Device.DeviceMsgGather.Keys)
            {
                if (key.Contains(s))
                {
                    for (int i = 0; i < c_Device.DeviceMsgGather[key].DevList.Count; i++)
                    {
                        DataRow dr = LlRealTimeTable.NewRow();
                        dr["设备名称"] = c_Device.DeviceMsgGather[key].DevList[i].DevName;
                        dr["测试值(mA)"] = "未测试";
                        LlRealTimeTable.Rows.Add(dr);
                    }
                }
            }
            JyLlobject.ReadJyLlCyNewstValue(s);
//            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadWaitLlRealTimeValue), null);
        }

        /// <summary>
        /// 把模拟量的值转换成实际的值，依据部标协议.
        /// </summary>
        /// <param name="AnalogType"></param>
        /// <param name="AnalogNo"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        static public ObjValue ConvertAnalogValue(string AnalogType, Int16 Value)
        {
            ObjValue retValue = new ObjValue();
            retValue.DecimalNum = 0;
            retValue.Value = 0xffff;
            retValue.ValueType = "";
            Int16 TmpValue = Value;
            int flag = (TmpValue & 0x8000) >> 15;
            int dic = (TmpValue & 0x6000) >> 13;
            TmpValue = (short)(TmpValue & 0x1fff);
            float tmp = (float)TmpValue;

            if (AnalogType.Contains("载频") || AnalogType.Contains("上边频") || AnalogType.Contains("下边频") || AnalogType.Contains("ZPW-2000A接口信息") || AnalogType.Contains("轨道编码"))
            {
                tmp = tmp * 10f;
                if (tmp > 81920) tmp = 0xffff;      //超过81920，则至为无效值
                retValue.DecimalNum = 0;
                retValue.Value = tmp;
                retValue.ValueType = "";
                return retValue;
            }
            else
            {
                //处理值和精度f
                if (dic == 1) tmp = tmp / 100f;
                else if (dic == 2) tmp = tmp / 10f;
                else if (dic == 3) tmp = tmp * 10f;
                if (tmp >= 0 && tmp <= 81.91)
                {
                    retValue.Value = tmp;
                    retValue.DecimalNum = 2;
                }
                else if (tmp >= 81.92 && tmp <= 81.94)
                {
                    tmp = 81.9f;
                    retValue.Value = tmp;
                    retValue.DecimalNum = 1;
                }
                else if (tmp >= 81.95 && tmp <= 81.99)
                {
                    tmp = 82.0f;
                    retValue.Value = tmp;
                    retValue.DecimalNum = 1;
                }
                else if (tmp >= 82.0 && tmp <= 819.1)
                {
                    retValue.Value = tmp;
                    retValue.DecimalNum = 1;
                }
                else if (tmp >= 819.2 && tmp <= 819.4)
                {
                    tmp = 819.0f;
                    retValue.Value = tmp;
                    retValue.DecimalNum = 1;
                }
                else if (tmp >= 819.5 && tmp <= 819.9)
                {
                    tmp = 820;
                    retValue.Value = tmp;
                    retValue.DecimalNum = 0;
                }
                else if (tmp >= 820 && tmp <= 81920)
                {
                    retValue.Value = tmp;
                    retValue.DecimalNum = 0;
                }
                else if (tmp > 81920)
                {
                    tmp = 0xffff;
                    retValue.Value = tmp;
                    retValue.DecimalNum = 0;
                }

                //处理标志位
                if (AnalogType.Contains("轨道电压") || AnalogType.Contains("轨道相位角") ||
                    AnalogType.Contains("主轨轨入电压") || AnalogType.Contains("轨出1电压") || AnalogType.Contains("轨出2电压") || AnalogType.Contains("小轨轨入电压"))
                {
                    if (flag == 1) retValue.ValueType = "调整";
                    else retValue.ValueType = "分路";
                }
                else if (AnalogType.Contains("电码化发送电流"))
                {
                    if (flag == 1) retValue.ValueType = "空闲";
                    else retValue.ValueType = "占用";
                }
                else if (AnalogType.Contains("道岔表示电压"))
                {
                    if (flag == 1) retValue.ValueType = "有表示";
                    else retValue.ValueType = "无表示";
                }
                else if (AnalogType.Contains("半自动闭塞") || AnalogType.Contains("站联电压"))
                {
                    if (flag == 0)
                    {
                        retValue.ValueType = "反向";
                        retValue.Value = 0f - retValue.Value;   //数值取反
                    }
                    else retValue.ValueType = "正向";
                }
                else if (AnalogType.Contains("环境模拟量") || AnalogType.Contains("高压不对称"))
                {
                    if (flag == 0)
                    {
                        retValue.ValueType = "";
                        retValue.Value = 0f - retValue.Value;   //数值取反
                    }
                }
            }
            return retValue;    
        }

        /// <summary>
        /// 根据模拟量类型和序号获得模拟量的实时值，转换过后的值
        /// </summary>
        /// <param name="AnalogType"></param>
        /// <param name="AnalogNo"></param>
        /// <returns></returns>
        static public ObjValue GetRealTimeAnalogValue(string AnalogType, int AnalogNo)
        {
            ObjValue retValue = new ObjValue();
            retValue.ValueType = "";
            retValue.DecimalNum = 0;
            retValue.Value = 0xffff;
            if (ReceiveAnalogData.ContainsKey(AnalogType))
            {
                if (AnalogNo>=0 && AnalogNo < ReceiveAnalogData[AnalogType].Count)
                {                    
                    Int16 TmpValue = ReceiveAnalogData[AnalogType][AnalogNo];   //取模拟量值
                    if((int)TmpValue == 0xffff)     //0xffff,直接返回无效
                    {
                        retValue.DecimalNum = 0;
                        retValue.Value = 0xffff;
                        retValue.ValueType = "";
                        return retValue;
                    }
                    retValue = ConvertAnalogValue(AnalogType ,TmpValue);
                }
            }
            return retValue;
        }

        /// <summary>
        /// 根据设备类型名，设备名，设备属性，获得该属性的实时值
        /// </summary>
        /// <param name="DevTypeName"></param>
        /// <param name="DevName"></param>
        /// <param name="Attri"></param>
        /// <returns></returns>
        static public ObjValue GetRealTimeAnalogValue(string DevTypeName, string DevName, string Attri)
        {
            AnalogObj t = c_Device.GetAnalogDevNo(DevTypeName, DevName, Attri);
            string s = c_Device.GetAnalogTypeName(t.type);
            ObjValue v = GetRealTimeAnalogValue(s, t.devNo);
            return v;
        }

        /// <summary>
        /// 根据开关量序号获得开关量的实时值
        /// </summary>
        /// <param name="No"></param>
        /// <returns></returns>
        static public int GetRealTimeKGLValue(int No)
        {
            if (No >= 0 && No < 2000 * 8)
            {
                int B = No / 8;
                int b = No % 8;
                byte t = ReceiveKGLData[B];
                return (t >> b) & 0x01;
            }
            return -1;
        }

        static public int GetRealTimeKGLValue(string DevTypeName, string DevName, string attriName)
        {
            AnalogObj t = c_Device.GetAnalogDevNo(DevTypeName, DevName, attriName);
            if (t.type == AnalogCodeType.None && t.devNo != -1)
            {
                return GetRealTimeKGLValue(t.devNo);
            }
            return -1;
        }

        /// <summary>
        /// 刷新模拟量实时值表，依据MSGgather配置的，依据设备填充设备属性的值。也就是各种设备类型的实时值。
        /// </summary>
        static private void DisposeAnalogRealTimeValue()    //刷新模拟量实时值
        {
            RealTimeValue_Analog.Clear();
            foreach (KeyValuePair<string, objMsgGatherStruct> li in c_Device.DeviceMsgGather)
            {
                string AnlogTypeName = li.Key;
                List<ObjRealTimeValue> tmpRealTimeValueList = new List<ObjRealTimeValue>();
                for (int i = 0; i < li.Value.DevList.Count; i++)    //一种模拟量类型所有的设备
                {
                    string TmpDevName = li.Value.DevList[i].DevName;
                    ObjRealTimeValue tmpRealTimeValue = new ObjRealTimeValue();
                    tmpRealTimeValue.DevName = TmpDevName;
                    for (int j = 0; j < li.Value.DevList[i].AnalogSet.Count; j++)       //一个设备所有的模拟量集合
                    {
                        int tmpAnalogNo = li.Value.DevList[i].AnalogSet[j];
                        AnalogCodeType tmpAnalogType = li.Value.ArrtiList[j].AnalogType;
                        if (tmpAnalogType == AnalogCodeType.None)   //开关量
                        {
                            int kglv = GetRealTimeKGLValue(tmpAnalogNo);
                            ObjValue kk = new ObjValue();
                            kk.DecimalNum = 0;
                            kk.Value = kglv;
                            kk.ValueType = "开关量";
                            tmpRealTimeValue.DevValue.Add(kk);
                        }
                        else
                        {
                            string tmp = c_Device.GetAnalogTypeName(tmpAnalogType);
                            ObjValue tmpValue = GetRealTimeAnalogValue(tmp, tmpAnalogNo);       //从实时值缓冲区获得该模拟量的实时数据
                            tmpRealTimeValue.DevValue.Add(tmpValue);
                        }
                    }
                    tmpRealTimeValueList.Add(tmpRealTimeValue);
                    if (RealTimeValue_Analog.ContainsKey(AnlogTypeName))
                    {
                        RealTimeValue_Analog[AnlogTypeName].Add(tmpRealTimeValue);
                    }
                    else RealTimeValue_Analog.Add(AnlogTypeName, tmpRealTimeValueList);
                }
            }
        }

        /// <summary>
        /// 刷星开关量实时值表，依据开关量表配置，填充开关量实时表格的数据
        /// </summary>
        static private void DisposeKglRealTimeValue()
        {
            for (int i = 0; i < KglRealTimeTable.Rows.Count; i++)
            {                
                DataRow dr = KglRealTimeTable.Rows[i];
                int m = GetRealTimeKGLValue(i);
                dr.BeginEdit();
                if (m == -1) dr["状态"] = "未知";
                else if (m == 1) dr["状态"] = "↑";
                else if (m == 0) dr["状态"] = "↓";
                dr.EndEdit();

            }
            KglRealTimeTable.AcceptChanges();
        }

        /// <summary>
        /// 处理逻辑处理层发送过来的命令回执信息
        /// </summary>
        static private void DisposeCommandRetValue()
        {
            foreach (objRevCommandType obj in ReceiveCommandData)
            {
                if (obj.type == 1)   //配置修改返回
                {
                    int Num = obj.value[0];
                    int m = 1;
                    for (int i = 0; i < Num; i++)
                    {
                        int okFlag = obj.value[m++];  //成功标记
                        int analogType = obj.value[m++];
                        int analogNo = obj.value[m] + obj.value[m+1] << 16;
                        m += 2;
                        //-----------修改前上限-------
                        int b = obj.value[m++]; //字节数
                        Array t = Array.CreateInstance(typeof(byte),b);
                        for (int k = 0; k < b; k++)
                        {
                            t.SetValue(obj.value[m++], k);                            
                        }
                        string s = t.ToString();
                        float f_up = float.Parse(s);
                        //-----------修改前下限--------
                        b = obj.value[m++];
                        t.Initialize();
                        for (int k = 0; k < b; k++)
                        {
                            t.SetValue(obj.value[m++], k);
                        }
                        s = t.ToString();
                        float f_dn = float.Parse(s);
                        //------------修改前分路上限-----
                        b = obj.value[m++];
                        t.Initialize();
                        for (int k = 0; k < b; k++)
                        {
                            t.SetValue(obj.value[m++], k);
                        }
                        s = t.ToString();
                        float f_fup = float.Parse(s);
                        //------------修改后上限----------
                        b = obj.value[m++];
                        t.Initialize();
                        for (int k = 0; k < b; k++)
                        {
                            t.SetValue(obj.value[m++], k);
                        }
                        s = t.ToString();
                        float b_up = float.Parse(s);
                        //------------修改后下限----------
                        b = obj.value[m++];
                        t.Initialize();
                        for (int k = 0; k < b; k++)
                        {
                            t.SetValue(obj.value[m++], k);
                        }
                        s = t.ToString();
                        float b_dn = float.Parse(s);
                        //------------修改后分路-----------
                        b = obj.value[m++];
                        t.Initialize();
                        for (int k = 0; k < b; k++)
                        {
                            t.SetValue(obj.value[m++], k);
                        }
                        s = t.ToString();
                        float b_fup = float.Parse(s);
                        //---------------------------------
                        if (okFlag == 0)    //修改配置失败
                        {
                            string typeName = c_Device.GetAnalogTypeName((AnalogCodeType)analogType);
                            MessageBox.Show(string.Format("配置修改失败,{0}_类型，序号_{1}", typeName, analogNo));
                        }
                        else
                        {
                            //修改内存中的值.
                            if (c_Device.IsValidAnalogType(analogType))
                            {
                                string keyString = c_Device.GetAnalogTypeName((AnalogCodeType)analogType);
                                if (c_Device.GD_AnalogConfig.ContainsKey(keyString))
                                {
                                    if (analogNo >= 0 && analogNo < c_Device.GD_AnalogConfig[keyString].AnalogList.Count)
                                    {
                                        c_Device.GD_AnalogConfig[keyString].AnalogList[analogNo].UpperThreshold = b_up;
                                        c_Device.GD_AnalogConfig[keyString].AnalogList[analogNo].LowerThreshold = b_dn;
                                        c_Device.GD_AnalogConfig[keyString].AnalogList[analogNo].FLUpperThreshold = b_fup;
                                    }
                                    else MessageInfo(null, new MessageInfoEventArgs("修改配置,序号越界"));
                                }
                                else if (c_Device.DC_AnalogConfig.ContainsKey(keyString))
                                {
                                    if (analogNo >= 0 && analogNo < c_Device.DC_AnalogConfig[keyString].AnalogList.Count)
                                    {
                                        c_Device.DC_AnalogConfig[keyString].AnalogList[analogNo].UpperThreshold = b_up;
                                        c_Device.DC_AnalogConfig[keyString].AnalogList[analogNo].LowerThreshold = b_dn;
                                        c_Device.DC_AnalogConfig[keyString].AnalogList[analogNo].FLUpperThreshold = b_fup;
                                    }
                                    else MessageInfo(null, new MessageInfoEventArgs("修改配置,序号越界"));
                                }
                                else if (c_Device.JC_AnalogConfig.ContainsKey(keyString))
                                {
                                    if (analogNo >= 0 && analogNo < c_Device.JC_AnalogConfig[keyString].AnalogList.Count)
                                    {
                                        c_Device.JC_AnalogConfig[keyString].AnalogList[analogNo].UpperThreshold = b_up;
                                        c_Device.JC_AnalogConfig[keyString].AnalogList[analogNo].LowerThreshold = b_dn;
                                        c_Device.JC_AnalogConfig[keyString].AnalogList[analogNo].FLUpperThreshold = b_fup;
                                    }
                                    else MessageInfo(null, new MessageInfoEventArgs("修改配置,序号越界"));
                                }
                                else if (c_Device.ZH_AnalogConfig.ContainsKey(keyString))
                                {
                                    if (analogNo >= 0 && analogNo < c_Device.ZH_AnalogConfig[keyString].AnalogList.Count)
                                    {
                                        c_Device.ZH_AnalogConfig[keyString].AnalogList[analogNo].UpperThreshold = b_up;
                                        c_Device.ZH_AnalogConfig[keyString].AnalogList[analogNo].LowerThreshold = b_dn;
                                        c_Device.ZH_AnalogConfig[keyString].AnalogList[analogNo].FLUpperThreshold = b_fup;
                                    }
                                    else MessageInfo(null, new MessageInfoEventArgs("修改配置,序号越界"));
                                }
                                else if (c_Device.YP_AnalogConfig.ContainsKey(keyString))
                                {
                                    if (analogNo >= 0 && analogNo < c_Device.YP_AnalogConfig[keyString].AnalogList.Count)
                                    {
                                        c_Device.YP_AnalogConfig[keyString].AnalogList[analogNo].UpperThreshold = b_up;
                                        c_Device.YP_AnalogConfig[keyString].AnalogList[analogNo].LowerThreshold = b_dn;
                                        c_Device.YP_AnalogConfig[keyString].AnalogList[analogNo].FLUpperThreshold = b_fup;
                                    }
                                    else MessageInfo(null, new MessageInfoEventArgs("修改配置,序号越界"));
                                }
                                else
                                {
                                    MessageInfo(null, new MessageInfoEventArgs("修改配置，模拟量类型错误"));
                                }
                            }
                            //上传服务器
                        }
                    }
                }
                else if (obj.type == 2) //绝缘测试返回值
                {
                    int No = obj.value[0];

                    int b = obj.value[1]; //字节数
                    Array t = Array.CreateInstance(typeof(byte), b);
                    for (int k = 0; k < b; k++)
                    {
                        t.SetValue(obj.value[2+k], k);
                    }
                    string s = t.ToString();
                    float value = float.Parse(s);
                   
                    if(No>=0 &&No<JyRealTimeTable.Rows.Count)
                    {
                        DataRow dr = JyRealTimeTable.Rows[No];
                        dr.BeginEdit();
                        dr["测试值(MΩ)"] = value.ToString();
                        int v0 = obj.value[3] + obj.value[4] << 6 + obj.value[5] << 16 + obj.value[6] << 24;
                        DateTime u = MySql.Time_tToDateTime(v0);
                        dr["测试时间"] = u;
                        dr.EndEdit();
                        //JyRealTimeTable.AcceptChanges();
                    }
                    else MessageInfo(null, new MessageInfoEventArgs("绝缘测试，返回序号错误"));
                }
                else if (obj.type == 4) //漏流测试返回值
                {
                    int No = obj.value[0];

                    int b = obj.value[1]; //字节数
                    Array t = Array.CreateInstance(typeof(byte), b);
                    for (int k = 0; k < b; k++)
                    {
                        t.SetValue(obj.value[2 + k], k);
                    }
                    string s = t.ToString();
                    float value = float.Parse(s);

                    if (No >= 0 && No < LlRealTimeTable.Rows.Count)
                    {
                        DataRow dr = LlRealTimeTable.Rows[No];
                        dr.BeginEdit();
                        dr["测试值(MΩ)"] = value.ToString();
                        int v0 = obj.value[3] + obj.value[4] << 6 + obj.value[5] << 16 + obj.value[6] << 24;
                        DateTime u = MySql.Time_tToDateTime(v0);
                        dr["测试时间"] = u;
                        dr.EndEdit();
                        //LlRealTimeTable.AcceptChanges();
                    }
                    else MessageInfo(null, new MessageInfoEventArgs("漏流测试，返回序号错误"));
                }
                else if (obj.type == 5) //报警确认值
                {
                    int Num = obj.value[0] + obj.value[1] << 16;
                    for (int i = 0; i < Num; i++)
                    {
                        int flag = obj.value[2 + i];
                        if (flag == 0) MessageInfo(null, new MessageInfoEventArgs("报警确认失败"));
                    }
                }
            }
        }
        /// <summary>
        /// 处理列控发送过来的信息，填充表格
        /// </summary>
        static private void DisposeLkRealTimeValue()
        {
            foreach (objRevLkType key in ReceiveLkData)
            {
                if(key.LkTypeName == "硬件平台A")
                {
                    c_LK.ParseProtecol_HostHardwarePlatform(ref HostHardwarePlatform, key.ValueList.ToArray());
                }
                else if (key.LkTypeName == "硬件平台B")
                {
                    c_LK.ParseProtecol_HostHardwarePlatform(ref HostHardwarePlatform, key.ValueList.ToArray());
                }
                else if (key.LkTypeName == "联锁接口进路信息")
                {
                   c_LK.ParseProtecol_LianSuoJieKouRouteInfo(ref LianSuoJieKouRouteInfo, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "联锁改方命令信息")
                {
                    c_LK.ParseProtecol_LianSuoGaiFangCommandInfo(ref LianSuoGaiFangCommandInfo, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "联锁改方回执信息")
                {
                    c_LK.ParseProtecol_LianSuoGaiFangCommandRet(ref LianSuoGaiFangCommandRet, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "站间改方命令")
                {
                    c_LK.ParseProtecol_ZhanJianGaiFangCommandInfo(ref ZhanJianGaiFangCommandInfo, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "站间改方回执")
                {
                    c_LK.ParseProtecol_ZhanJianGaiFangCommandRet(ref ZhanJianGaiFangCommandRet, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "站间边界信息")
                {
                    c_LK.ParseProtecol_ZhanJianBoundaryInfo(ref ZhanJianBoundaryInfo, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "临时限速状态")
                {
                    c_LK.ParseProtecol_TemporaryLimitSpeedState(ref TemporaryLimitSpeedState, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "轨道区段编码信息")
                {
                    c_LK.ParseProtecol_SectionEncodeInfo(ref SectionEncodeInfo, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "状态全体信息")
                {
                    c_LK.ParaseProtecol_AllStatueInfo(ref Statue_Info, key.ValueList.ToArray());
                }
                else if(key.LkTypeName == "应答器报文编码信息")
                {
                    c_LK.ParaseProtecol_TransponderEncodeInfo(ref TransponderEncodeInfo, key.ValueList.ToArray());
                }
                else if (key.LkTypeName == "无配线站方向口信息")
                {
                    c_LK.ParseProtecol_SendToLianSuoInfo(ref SendToLianSuoInfo, key.ValueList.ToArray());
                }                
            }
        }        
    }
}
